// pages/main-person-new/main-person.js
const app = getApp();
const _user = require("../../utils/User.js")
const api = require("../../server/Api.js");
const util = require("../../utils/util.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabBarHeight: 0,
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    Custom: app.globalData.Custom,
    headUrl: "",
    userInfo: null, //用户信息
    isLogin: false,
    active: -1,
    curPage: 1,
    pageSize: 6,
    hasMore: true,
    showPayTypeDialog: false,
    showCancelDialog: false, //取消订单弹窗
    curPayType: 0,
    operType: 1, //1:取消订单  2：删除订单
    curOrder: {}, //按钮操作的当前id
    curOrderIndex: 0, //当前订单的索引
    emptyType: 2,
    curTap: 3,
    scrollLeft: 0,
    orderTotals: 0,
    tabTitles: [{
      name: "待提货",
      type: 3
    }, {
      name: "已完成",
      type: 4
    }],
    opertionBtns: {
      1: [{
        name: '开始配送',
        color: 'red'
      }],
      2: [{
        name: '确认送达',
        color: 'red'
      }],
      3: [{
        name: '提醒提货',
        color: 'gray'
      }, {
        name: '立即核销',
        color: 'gray'
      }],
      4: [{
        name: '查看订单',
        color: 'gray'
      }],
      5: [{
        name: '查看订单',
        color: 'gray'
      }]
    },
    count2: 0,
    count3: 0,
    shopInfo: {},
    tonotify: false,
    chooseAll: false,
    dates: [],
    items: {}, //总商品数
    memberId: ""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      tabBarHeight: app.globalData.StatusBar < 30 ? 49 : 83
    })
    let active = 1;
    if (options.active) {
      active = options.active;
    }
    this.setData({
      active: active
    });
    let userBean = app.globalData.userBean;

    var isLogin = false;
    var headUrl = app.globalData.defaultHeadUrl;
    if (userBean && userBean.consumerId) {
      isLogin = true;
      headUrl = userBean.avatar || app.globalData.defaultHeadUrl;
    } else {
      isLogin = false;
    }
    this.setData({
      isLogin: isLogin,
      userInfo: userBean,
      headUrl: headUrl,
    })

    this.getShopInfo();
    if (active == 0) {
      this.goShopOrder()
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    //如果没登陆，进行登录
    if (!this.data.isLogin) {
      tt.stopPullDownRefresh();
      tt.switchTab({
        url: '../main-person-new/main-person'
      })
    }
    this.getOrderCount();
  },

  getOrderCount() {
    let that = this;
    that.setData({
      count2: 0,
      count3: 0
    })
    if (!that.data.isLogin) {
      return
    }
    this.queryOrderCount(2, count => {
      that.setData({
        count2: count
      })
    })
    this.queryOrderCount(3, count => {
      that.setData({
        count3: count
      })
    })
  },

  queryOrderCount(status, callback) {
    let that = this;
    let userBean = app.globalData.userBean;
    let prams = {
      pageSize: 1,
      pageNumber: 1,
      userId: userBean.consumerId,
      status: status
    };
    api.queryOrderList(prams).then(res => {
      callback(res.total)
    })
  },

  changeUser: function(e) {
    let that = this;
    tt.showModal({
      title: '切换账号',
      content: '',
      success: function(e) {
        if (e.confirm) {
          _user.exit()
          app.globalData.userBean = null;
          app.globalData.userInfo = null;
          that.toLogin();
        }
      }
    })
  },
  toLogin: function(e) {
    tt.navigateTo({
      url: '../login/login',
    })
  },
  toChangeUser: function() {
    console.log("1");
    tt.switchTab({
      url: '../main-person-new/main-person',
    })
  },
  //下拉啊刷新
  onPullDownRefresh: function() {
    this.refreshData();
  },

  //刷新列表
  refreshData: function() {
    var that = this;
    this.setData({
      hasMore: true,
    })
    this.queryOrderList(1, this.data.pageSize);
    tt.pageScrollTo({
      scrollTop: 0,
      duration: 300
    })
  },

  //上拉加载
  onReachBottom: function() {
    if (this.data.hasMore == false) return;
    let page = this.data.curPage + 1;
    this.queryOrderList(page, this.data.pageSize);
  },

  //分页查询订单
  queryOrderList: function(page, pageSize) {
    let that = this;
    let userBean = app.globalData.userBean;
    let orderStatus = this.data.curTap;
    // tt.getLocation({
    //   type: 'gcj02',
    //   success: res => {

    //   }
    // })
    let prams = {
      pageSize: that.data.pageSize,
      pageNumber: page,
      userId: userBean.consumerId,
      storeId: app.globalData.userShopId[0].id,
      status: orderStatus,
      latitude: 0,
      longitude: 0
    };
    app.showLoading()
    api.queryStoreOrderListByDeliveryTime(prams).then(res => {
      //请求成功
      tt.hideLoading()
      tt.stopPullDownRefresh();
      that.querySuccess(res, page)
      that.setData({
        emptyType: 2
      })
    }).catch(msg => {
      tt.hideLoading()
      tt.stopPullDownRefresh();
      that.setData({
        emptyType: 101
      })
      var message = typeof msg == "string" ? msg : msg.message;
      app.showToast(message);
    })
  },

  //查询成功
  querySuccess: function(res, curPage) {
    let that = this;
    //数据
    let records = res.records;
    let maxPage = parseInt(res.pages);
    var items = curPage == 1 ? {} : this.data.items;
    var dates = curPage == 1 ? [] : this.data.dates;
    if (records) {
      for (let i = 0; i < records.length; i++) {
        records[i] = util.formatOrderStatus(records[i])
        let date = app.getZtDate(records[i].deliveryTime)
        if (!items[date]) {
          items[date] = {};
          dates.push(date);
          items[date].orders = [];
          items[date].choosed = that.data.chooseAll;
        }
        records[i].choosed = items[date].choosed;
        items[date].orders.push(records[i]);
      }
    }
    that.setData({
      hasMore: maxPage > curPage,
      dates: dates,
      items: items,
      curPage: curPage
    })
    if (that.data.curTap == 3) {
      that.setData({
        orderTotals: res.total
      })
    }
  },

  // 按钮操作
  opertionTap: function(e) {
    let order = e.currentTarget.dataset.order;
    let shopIndex = e.currentTarget.dataset.shopindex;
    let btnName = e.currentTarget.id;
    let opertionBtns = this.data.opertionBtns;
    this.setData({
      curOrder: order,
      curOrderIndex: shopIndex
    })


    switch (btnName) {
      case "取消订单":
        this.setData({
          operType: 1
        })
        this.showCancelDialog();
        break;
      case "删除订单":
        this.setData({
          operType: 2
        })
        this.showCancelDialog();
        break;
      case "开始配送":
        this.updateOrderStatus(order.orderId, 1)
        break;
      case "确认送达":
        this.updateOrderStatus(order.orderId, 2)
        break;
      case "扫码核销":
        this.toscan();
        break;
      case "查看订单":
        tt.navigateTo({
          url: '../shop-order-detail/shop-order-detail?orderId=' + order.orderId,
        })
        break
      case "提醒提货":
        api.notifyBuyersByOrderId(order.orderId).then(() => {
          app.showToast("已成功提醒客户")
        }).catch(msg => {
          let message = typeof msg == "string" ? msg : msg.message;
          app.showToast("通知失败!" + message);
        })
        break
      case "立即核销":
        this.hexiao(order)
        break
    }
  },

  updateOrderStatus(orderId, status) {
    api.UpdateOrderStatus(orderId, status).then(() => {
      this.refreshData();
    }).catch(msg => {
      let message = typeof msg == "string" ? msg : msg.message;
      app.showToast(message);
    })
  },

  //请求删除or取消订单
  onConfirm: function() {
    let that = this;
    let curOrder = this.data.curOrder;
    let curOrderIndex = this.data.curOrderIndex;

    let operType = this.data.operType;
    app.showLoading()
    if (operType == 2) {
      api.deleteOrder(curOrder.orderId).then(res => {
        var shops = that.data.items;
        shops.splice(curOrderIndex, 1);
        that.setData({
          items: shops
        })
      }).catch(msg => {
        let message = typeof msg == "string" ? msg : msg.message;
        app.showToast(message);
      })
    } else {
      api.cancelOrder(curOrder.orderId).then(res => {
        let itemIndex = "items[" + curOrderIndex + "]"
        curOrder.orderCnStatus = "已取消";
        curOrder.orderStatus = 0;
        that.setData({
          [itemIndex]: curOrder
        })
      }).catch(msg => {
        let message = typeof msg == "string" ? msg : msg.message;
        app.showToast(message);
      })
    }
  },

  //显示是否弹出取消订单的操作
  showCancelDialog: function() {
    this.setData({
      showCancelDialog: true,
    })
  },

  //头部导航栏选择事件
  tabSelect: function(e) {
    let tabBean = e.currentTarget.dataset.tab;
    if (tabBean != 3) {
      this.hideNotify();
    }
    this.setData({
      curTap: tabBean.type,
      scrollLeft: (e.currentTarget.dataset.id - 1) * 60
    })
    this.refreshData();
  },

  //显示支付方式弹窗
  showPayTypeDialog: function() {
    this.setData({
      showPayTypeDialog: true,
    })
  },
  //隐藏所有弹窗
  hiddenDialog: function(e) {
    this.setData({
      showPayTypeDialog: false,
      showCancelDialog: false
    })
  },
  toscan: function() {
    let that = this;
    // tt.navigateTo({
    //   url: '../shop-order-list/shop-order-list?userId=2',
    // })
    // return;
    // 只允许从相机扫码
    tt.scanCode({
      //onlyFromCamera: true,
      success(res) {
        console.log(res)
        tt.navigateTo({
          url: '../shop-order-list/shop-order-list?userCode=' + res.result,
        })
        // api.verificationOrder(res.result, app.globalData.userShopId[0].id).then(() => {
        //   //app.showToast("订单已核销")
        //   tt.showModal({
        //     title: '订单已核销',
        //     showCancel: false
        //   })
        //   that.refreshData()
        // }).catch(msg => {
        //   let message = typeof msg == "string" ? msg : msg.message;
        //   app.showToast("核销失败!" + message);
        // })
      }
    })
  },
  goShopOrder: function() {
    this.setData({
      active: 0
    })
    this.refreshData();
  },
  goShopMy: function() {
    this.setData({
      active: 1,
    })
    this.hideNotify();
  },
  toShopInfo: function() {
    tt.navigateTo({
      url: '../shop-info/shop-info?type=1&id=' + app.globalData.userShopId[0].id,
    })
  },
  getShopInfo: function() {
    const that = this;
    api.getShopInfo(app.globalData.userShopId[0].id).then(res => {
      console.log("店铺信息:", res);
      that.setData({
        shopInfo: res
      })
    }).catch(msg => {
      let message = typeof msg == "string" ? msg : msg.message;
      app.showToast(message);
    })
  },
  showShareDialog() {
    this.setData({
      showShareDialog: true
    })
  },
  hiddenShareDialog() {
    this.setData({
      showShareDialog: false
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    let that = this;
    let userId = "";
    let userInfo = app.globalData.userBean;
    if (userInfo && userInfo.consumerId) {
      userId = userInfo.consumerId
    }
    return {
      title: '好获拼拼-' + that.data.shopInfo.storeName,
      path: 'pages/index/index?id=' + that.data.shopInfo.shopId + "&uid=" + userId,
      imageUrl: 'https://obs.cn-north-1.myhuaweicloud.com/obs-7d37/hh_shequ/index_share.png',
      success: function(res) {
        tt.showToast('转发成功');
      },
      fail: function() {
        tt.showToast('转发失败');
      }
    }
  },
  toSetPosition() {
    let that = this;
    tt.showModal({
      title: '店铺定位',
      content: '确认把您目前所在的位置更新为您的店铺定位位置吗？',
      success: function(e) {
        if (e.confirm) {
          tt.getLocation({
            type: 'gcj02',
            success: res => {
              let storeDtos = [{
                id: app.globalData.userShopId[0].id,
                latitude: res.latitude,
                longitude: res.longitude
              }]
              api.batchUpdateStores(storeDtos).then(res => {
                tt.showToast('更新店铺定位成功');
              }).catch(res => {
                app.showToast('更新店铺定位失败');
              });
            }
          })
        }
      }
    })
  },
  toAccount() {
    tt.navigateTo({
      url: '../shop-account/index',
    })
  },
  toIdcard() {
    app.showToast("功能未开放")
  },
  showNotify() {
    this.setData({
      tonotify: true
    });
  },
  hideNotify() {
    this.setData({
      tonotify: false,
      chooseAll: false
    });
    this.setChooseByAll()
  },
  chooseAll() {
    this.setData({
      chooseAll: !this.data.chooseAll
    });
    this.setChooseByAll()
  },
  setChooseByAll() {
    let that = this;
    let items = that.data.items;
    for (let i = 0; i < that.data.dates.length; i++) {
      items[that.data.dates[i]].choosed = that.data.chooseAll;
      for (let x = 0; x < items[that.data.dates[i]].orders.length; x++) {
        items[that.data.dates[i]].orders[x].choosed = items[that.data.dates[i]].choosed;
      }
    }
    that.setData({
      items: items
    })
  },
  setChooseByDate(date) {
    let that = this;
    let items = that.data.items;
    for (let x = 0; x < items[date].orders.length; x++) {
      items[date].orders[x].choosed = items[date].choosed;
    }
    that.setData({
      items: items
    })
  },
  chooseDate(e) {
    console.log(e)
    let that = this;
    let items = that.data.items;
    items[e.currentTarget.dataset.date].choosed = !(items[e.currentTarget.dataset.date].choosed)
    this.setData({
      items: items
    });
    this.setChooseByDate(e.currentTarget.dataset.date)
  },
  chooseOrder(e) {
    let that = this;
    let items = that.data.items;
    items[e.currentTarget.dataset.date].orders[e.currentTarget.dataset.index].choosed = !(items[e.currentTarget.dataset.date].orders[e.currentTarget.dataset.index].choosed)
    this.setData({
      items: items
    });
  },
  hexiao(order) {
    let that = this;
    console.log(order)
    tt.showModal({
      title: '核销订单',
      content: '确认核销该订单吗？',
      success: function(res) {
        if (res.confirm) {
          api.verificationOrder(order.code, app.globalData.userShopId[0].id).then(() => {
            tt.showModal({
              title: '订单已核销',
              showCancel: false
            })
            that.refreshData()
          }).catch(msg => {
            let message = typeof msg == "string" ? msg : msg.message;
            app.showToast("核销失败!" + message);
          })
        }
      }
    })
  },
  oneKeyNotify() {
    let date = tt.getStorageSync("OneKeyNotify");
    let curDate = new Date();
    if (date && date.getFullYear() === curDate.getFullYear() && date.getMonth() === curDate.getMonth() && date.getDate() === curDate.getDate()) {
      app.showToast("今天已发送过一键提醒,不能再次发送!");
      return;
    }
    let that = this;
    tt.showModal({
      title: '提示',
      content: '是否确定通知买家过来提货？（仅当前可提货的订单）',
      success: function(res) {
        if (res.confirm) {
          api.notifyBuyersByStoreId(app.globalData.userShopId[0].id).then(() => {
            tt.setStorageSync("OneKeyNotify", new Date());
            tt.showModal({
              title: '提示',
              content: '当前可提货的订单，已短信通知买家过来提货。',
              showCancel: false
            })
          }).catch(msg => {
            let message = typeof msg == "string" ? msg : msg.message;
            app.showToast("一键提醒失败!" + message);
          })
        }
      }
    })
  }
})